﻿using System;
using System.Web.Mvc;
using BusinessBingo.Model;
using BusinessBingo.Web.Bindings.Interfaces;
using BusinessBingo.Web.Infrastructure.InfoStores.Interfaces;
using BusinessBingo.Web.Infrastructure.InfoStores.Keys;

namespace BusinessBingo.Web.Bindings
{
    /// <summary>
    /// ModelBinder for cookiedata
    /// </summary>
    public class CurrentUserBinder : IModelBinder<CurrentUserData>
    {
        /// <summary>
        /// Field for CookieRepo
        /// </summary>
        private ICookieRepository _cookieRepository;

        /// <summary>
        /// Ctor for instanciation
        /// </summary>
        /// <param name="cookieRepository">Implementation of ICookieRepository</param>
        public CurrentUserBinder(ICookieRepository cookieRepository)
        {
            this._cookieRepository = cookieRepository;
        }

        /// <summary>
        /// BindModel method on IModelBinder
        /// </summary>
        /// <param name="controllerContext">controllercontext for modelbinding</param>
        /// <param name="bindingContext">bindingcontext for modelbinding</param>
        /// <returns>CookieData</returns>
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }
            if (bindingContext == null)
            {
                throw new ArgumentNullException("bindingContext");
            }
            
            CurrentUserData cookieData = new CurrentUserData();
            if (this._cookieRepository.HasElement(CookieKeys.UserId) == true)
                cookieData.UserId = new Guid(this._cookieRepository.GetElement(CookieKeys.UserId));
            if (this._cookieRepository.HasElement(CookieKeys.GameId) == true)
                cookieData.GameId = new Guid(this._cookieRepository.GetElement(CookieKeys.GameId));

            if (cookieData.GameId == Guid.Empty || cookieData.UserId == Guid.Empty)
                return default(CurrentUserData);

            return cookieData;
        }
    }
}